package cn.com.git.workflow.server.service.impl;

import cn.com.git.workflow.server.service.WebSocketService;
import cn.com.git.common.socket.WebSocketParam;
import cn.com.git.common.util.object.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangzhenfu
 * @Description
 * @date 2020/3/12 15:02
 */
@ServerEndpoint("/webSocket/{id}/{name}")
@Service
public class WebSocketServiceImpl implements WebSocketService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServiceImpl.class);
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象
    private static Map<Integer, Session> webSocketSet = new ConcurrentHashMap<>();
    private Session getSession(Integer id){
        return webSocketSet.get(id);
    }
    private Integer getKey(Session session){
        Integer key = null ;
        for(Map.Entry<Integer,Session>  entry:webSocketSet.entrySet()){
            if(session.equals(entry.getValue())){
                key = entry.getKey();
                break;
            }
        }
        return key;
    }

    //开启会话
    @OnOpen
    public void onOpen(Session session, @PathParam("id") Integer id, @PathParam("name") String name) throws Exception {
        webSocketSet.put(id,session);
        LOGGER.info("Open a websocket. id={}, name={}", id, name);
    }

    @OnClose
    public void onClose(Session session) {
        Integer key = getKey(session);
        if(key!=null){
            webSocketSet.remove(key);
            LOGGER.info("Close a websocket. ");
        }
    }

    @OnMessage
    public void onMessage(Session session,String message) {
        LOGGER.info(message);
        WebSocketParam param = null;
        if(StringUtils.isNotEmpty(message)){
            param = JSONUtils.fromJson(message,WebSocketParam.class);
        }
        if(param == null){
            return;
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        Integer key = getKey(session);
        LOGGER.error("key "+ key +",Error while websocket. ", error);
    }

    @Override
    public void sendMessage(String message) {
        Session session = getSession(1);
        if (session!=null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
